package com.dhh.sky.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import com.dhh.sky.R;
import com.dhh.sky.activity.AudioPlayerActivity;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.SongsManager;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class MusicPlayerService extends Service {
	private Notification notification;
	private NotificationManager notificationManager;
	private final IBinder mBinder = new AudioPlaybackServiceBinder();
	private MediaPlayer player;
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	private String currentSongTitle;
	private String currentSongPath;
	private int currentSongIndex;

	@Override
	public void onCreate() {
		super.onCreate();
		player = createPlayer();
		notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	private MediaPlayer createPlayer(){
		MediaPlayer player = new MediaPlayer();
		player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mediaPlayer) {
				// onPlayerPrepared(mediaPlayer);
			}
		});

		player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
			@Override
			public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
				mediaPlayer.reset();
				cancelNotification();
				return true;
			}
		});

		player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mediaPlayer) {
				ArrayList<HashMap<String, String>> songsList = new SongsManager().getPlayList();
				if(isRepeat){
					playSong(currentSongIndex);
				} else if(isShuffle){
					// shuffle is on - play a random song
					Random rand = new Random();
					currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
					playSong(currentSongIndex);
				} else{
					// no repeat or shuffle ON - play next song
					if(currentSongIndex < (songsList.size() - 1)){
						playSong(currentSongIndex + 1);
						currentSongIndex = currentSongIndex + 1;
					}else{
						cancelNotification();
					}
				}
			}
		});

		return player;
	}
	
	private void createNotification(){
		Intent intent = new Intent(this,AudioPlayerActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);		
		
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
		Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.ic_stat_music);
		builder.setLargeIcon(largeIcon);
		builder.setContentIntent(pendingIntent);
		builder.setContentTitle(this.getCurrentSongTitle());
		builder.setContentText(this.getSongArtist());
		
		notification = builder.getNotification();		
		notification.icon = R.drawable.ic_stat_music;
		//notification.flags |= Notification.fl;		
		notificationManager.notify(Constant.NOTIFICATION_MUSIC_ID, notification); 
	}
	
	private void cancelNotification(){
		notificationManager.cancel(Constant.NOTIFICATION_MUSIC_ID);
	}

	public void playSong(String path) {

	}

	public void  playSong(int songIndex){
		// Play song
		try {
			cancelNotification();
			ArrayList<HashMap<String, String>> songsList = new SongsManager().getPlayList();
			if(songsList.size()>0){
				currentSongIndex = songIndex;
	        	player.reset();	
	        	currentSongPath = songsList.get(songIndex).get(Constant.SONG_PATH);
	        	currentSongTitle = songsList.get(songIndex).get(Constant.SONG_TITLE);
	        	player.setDataSource(currentSongPath);
	        	player.prepare();
	        	player.start();
	        	
	        	createNotification();
			}
		} catch (Exception e) {
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
	
	public void seekTo(int position){
		player.seekTo(position);
	}
	
	public int getDuration(){
		int duration = 1000;
		if(player!=null)
			duration = player.getDuration();
		return duration;
	}
	
	public int getCurrentPosition(){
		int position = 0;
		if(player!=null)
			position = player.getCurrentPosition();
		return position;
	}

	public void pausePlay() {
		if(player!=null){
			player.pause();
		}
		
		cancelNotification();
	}	
	
	public void startPlay() {
		if(player!=null){
			player.start();
		}
		
		createNotification();
	}
	
	public boolean isPlaying(){
		boolean flag = false;
		if(player!=null){
			flag = player.isPlaying();
		}
		
		return flag;
	}	

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (player != null) {
			try {
				player.stop();
				player.reset();
				player.release();
				player = null;
			} catch (IllegalStateException e) {
				Log.e(Constant.TAG, e.getMessage(), e);
			}
		}
	}

	public class AudioPlaybackServiceBinder extends Binder {
		public MusicPlayerService getService() {
			return MusicPlayerService.this;
		}
	}

	public String getCurrentSongTitle() {
		return currentSongTitle;
	}
	
	public String getCurrentSongPath() {
		return currentSongPath;
	}
	
	public String getSongArtist(){
		MediaMetadataRetriever mmr = new MediaMetadataRetriever();
		mmr.setDataSource(getCurrentSongPath());
		String name = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
		if(name==null || name.length()==0){
			name = "Unknow Artist";
		}
		return name;
	}
	

	public boolean isShuffle() {
		return isShuffle;
	}

	public void setShuffle(boolean isShuffle) {
		this.isShuffle = isShuffle;
	}

	public boolean isRepeat() {
		return isRepeat;
	}

	public void setRepeat(boolean isRepeat) {
		this.isRepeat = isRepeat;
	}

	public int getCurrentSongIndex() {
		return currentSongIndex;
	}

	public void setCurrentSongIndex(int currentSongIndex) {
		this.currentSongIndex = currentSongIndex;
	}

}
